package com.sxkj.web.runnable;

import com.sxkj.service.redis.RedlockService;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class RedissonRunnable implements Runnable {

    /** 处理main线程阻塞（等待所有子线程） */
    private CountDownLatch countDown;

    /** 线程名字 */
    private String  threadName;

    private RedissonClient redissonClient;

    public RedissonRunnable(CountDownLatch countDownLatch, String threadName
    , RedissonClient redissonClient) {
        this.countDown = countDownLatch;
        this.redissonClient = redissonClient;
        this.threadName = threadName;
    }

    @Override
    public void run() {
//        System.out.println( "[" + threadName + "] Running ! [countDownLatch.getCount() = " + countDown.getCount() + "]." );
//        String resourceName = "REDLOCK_KEY";
        // 向1个redis实例尝试加锁
        RLock lock = redissonClient.getLock("REDLOCK_KEY");
        RedissonRedLock redLock = new RedissonRedLock(lock);
        try {
            // isLock = redLock.tryLock();
            // 500ms拿不到锁, 就认为获取锁失败。10000ms即10s是锁失效时间。
            boolean isLock = redLock.tryLock(500, 10000, TimeUnit.MILLISECONDS);
            if (isLock) {
                //TODO 获取到锁，处理相关业务
                System.out.println(" 获取到锁，处理相关业务");
                Thread.sleep(200);  //就按照每个业务处理平均200ms完成
//                System.out.println( "获取锁结果："+isLock);
                //TODO if get lock success, do something;
            }else{
                //TODO 重复 retryCount 次 放弃 或者重复请求小于锁过期时间 放弃
                System.out.println("已上锁了....");
            }
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            // 无论如何, 最后都要解锁
            redLock.unlock();
            countDown.countDown();
        }
    }

}
